package cz.fit.vutbr.pis2012.augeaswh.control.ekonom.orders;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import cz.fit.vutbr.pis2012.augeaswh.managers.OrdersManager;
import cz.fit.vutbr.pis2012.augeaswh.managers.SubscriberManager;
import cz.fit.vutbr.pis2012.augeaswh.persistence.Order;
import cz.fit.vutbr.pis2012.augeaswh.persistence.StockType;
import cz.fit.vutbr.pis2012.augeaswh.persistence.Subscriber;

@ManagedBean
@SessionScoped
public class OrdersEditorBean implements Serializable {
	private static final long serialVersionUID = 226281265392763838L;
	@EJB
	private OrdersManager om;
	@EJB
	private SubscriberManager sm;
	private Order order;
	private String name;
	private Date incomeDate;
	private Subscriber subscriber;
	
	public OrdersEditorBean() {
		setOrder(null);
	}
	
	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
		name="";
		incomeDate=Calendar.getInstance().getTime();
		subscriber=null;
		if(this.order!=null) {
			this.name=order.getName();
			this.incomeDate=order.getIncomeDate();
			this.subscriber=order.getSubscriber();
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Date getIncomeDate() {
		return incomeDate;
	}

	public void setIncomeDate(Date incomeDate) {
		this.incomeDate = incomeDate;
	}

	public Subscriber getSubscriber() {
		return subscriber;
	}
	
	public void setSubscriber(Subscriber subscriber) {
		this.subscriber = subscriber;
	}

	public String submit() {
		
		if(order==null) {
			this.order=new Order();
		}
		this.order.setName(name);
		this.order.setIncomeDate(new Timestamp(incomeDate.getTime()));
		this.order.setSubscriber(subscriber);
		om.save(order);
		setOrder(null);
		return "back";
	}
	
	public String getTitle() {
		if(this.order==null) {
			return "New order";
		}
		else {
			return "Edited order \""+this.order.getName()+"\"";
		}
	}
	
	public List<Subscriber> getSubscribers() {
		return sm.getSubscribers();
	}
}
